<template>
  <el-dialog
    title="竣工结算明细"
    :visible.sync="show"
    width="1000px"
    center
    :close-on-click-modal="false"
  >
    <el-form
      ref="form"
      :rules="rules"
      style="padding-top: 10px"
      :model="form"
      label-width="120px"
    >
      <div class="com-form-title">基础信息</div>
      <el-row>
        <el-col :span="8">
          <el-form-item label="项目名称" prop="projectName">
            <!-- <el-input v-model="form.projectName" readonly placeholder="自动生成" /> -->
            <el-input
              v-model="form.projectName"
              readonly
              :disabled="disableForm || optType !== 'add'"
              @click.native="
                optType === 'add' ? (showTargetSetListModal = true) : null
              "
            >
              <i
                slot="suffix"
                class="el-input__icon el-icon-circle-plus-outline"
              />
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="项目结算总额" prop="projectSettleAmount">
            <!-- <el-input v-model="form.projectName" readonly placeholder="自动生成" /> -->
            <el-input v-model="form.projectSettleAmount" placeholder="自动生成" />
          </el-form-item>
        </el-col>
      </el-row>

      <com-table
        ref="detailTable"
        v-model="selectRow"
        highlight-current-row
        default-expand-all
        :data="targetList"
        :columns="columns"
        :no-page="true"
        height="300"
        row-key="number"
        :tree-props="{ children: 'childrens', hasChildren: 'hasChildren' }"
      >
        <template v-slot:unitPrice="{ row }">
          <el-input v-model="row.unitPrice" @input="getSumPrice" />
        </template>
        <template v-slot:contractWorkVolume="{ row }">
          <el-input v-model="row.contractWorkVolume" />
        </template>
        <template v-slot:actualCompletion="{ row }">
          <el-input v-model="row.actualCompletion" @input="getSumPrice" />
        </template>
        <template v-slot:sumPrice="{ row }">
          <el-input v-model="row.sumPrice" @input="displaySumPrice" />
        </template>
        <template v-slot:remark="{ row }">
          <el-input v-model="row.remark" />
        </template>
      </com-table>
      <el-button
        style="margin-top: 10px"
        type="primary"
        @click="showFileModal = true"
      >附件资料({{ fileList.length }})</el-button>
      <file-uploader
        v-model="fileList"
        :show-modal.sync="showFileModal"
        :disabled="disableForm"
        :can-download="optType === 'detail'"
      />
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="show = false">取 消</el-button>
      <el-button type="primary" @click="saveDoc">确 定</el-button>
    </span>
    <project-list
      :show-modal.sync="showTargetSetListModal"
      @getSelectedRows="getSelectedRows"
    />
  </el-dialog>
</template>

<script>
import {
  addCompletionSettleInfo,
  updateCompletionSettleInfo,
  getCompletionSettleInfoDetail
} from '@/api/completedManage'
import { workflowStatus } from '@/utils/dicData'
import fileUploader from '@/components/FileUploader'
import ProjectList from '@/components/TreeModal/project'
import moment from 'moment'
export default {
  name: 'AddProjectTotalCostPlanInfo',
  components: {
    fileUploader,
    ProjectList
  },
  props: {
    showModal: {
      type: Boolean,
      default: false
    },
    optType: {
      type: String,
      default: 'add'
    },
    dir: {
      type: Object,
      default() {
        return {}
      }
    },
    data: {
      type: Object,
      default() {
        return {}
      }
    }
  },
  data() {
    return {
      showFileModal: false,
      selectRow: null,
      targetList: [],
      workflowStatus,

      addType: '', // same   under
      visible: false,
      showAdd: false,
      selectedNode: null,
      form: {
        projectName: '',
        projectSettleAmount: ''
      },
      columns: [
        {
          fixed: 'left',
          label: '细目编号',
          width: '150',
          prop: 'number'
        },
        {
          fixed: 'left',
          label: '细目名称',
          width: '150',
          prop: 'name'
        },
        {
          label: '清单单位',
          width: '90',
          prop: 'unit'
        },
        {
          label: '单价',
          slot: 'unitPrice',
          width: '100'
        },
        {
          label: '合同工作量',
          width: '120',
          slot: 'contractWorkVolume'
        },

        {
          label: '实际完工量',
          width: '120',
          slot: 'actualCompletion'
        },
        {
          label: '合价',
          width: '120',
          slot: 'sumPrice'
        },
        {
          label: '描述',
          width: '108',
          slot: 'remark'
        }

        // {
        //   fixed: 'right',
        //   prop: 'options',
        //   slot: 'options'
        // }
      ],
      showTargetSetListModal: false,
      fileList: [],
      rules: {
        projectName: [
          { required: true, message: '项目名称', trigger: 'change' }
        ]
        // projectSettleAmount: [
        //   { required: true, message: "项目结算总额", trigger: "change" },
        // ],
        // unifiedSocialCreditCode: [
        //   { required: true, message: '统一社会信用代码', trigger: 'change' }
        // ]
      },
      provinceData: [],
      cityData: [],
      total: 0
    }
  },
  computed: {
    disableForm() {
      return this.optType === 'detail'
    },
    show: {
      get() {
        return this.showModal
      },
      set(val) {
        this.$emit('update:showModal', val)
      }
    }
  },
  watch: {
    showModal(val) {
      if (val && this.optType !== 'add') {
        this.getDocDetail(this.data.id)
        this.$nextTick(() => {
          Object.keys(this.form).forEach((key) => {
            const source = this.data[key]
            if (typeof source === 'boolean') {
              this.form[key] = source ? 1 : 0
            } else {
              this.form[key] = source
            }
          })
        })
      } else if (!val) {
        this.fileList = []
        this.targetList = []
        this.$refs.form.resetFields()
      }
    }
  },
  mounted() {},
  methods: {
    dateFormat(data) {
      if (data) {
        return moment(data).format('YYYY-MM-DD')
      } else {
        return ''
      }
    },
    getSelectedRows(obj) {
      // 将值赋给
      this.form = {
        projectName: obj.row.projName
      }
      const formateData = (data) => {
        return data.map((item) => {
          const { number, name, unit, childrens, parentId, price, contractWorkVolume } = item
          return {
            parentId,
            number,
            name,
            unit,
            ...(childrens
              ? {
                childrens: formateData(childrens)
              }
              : {}),
            constSumPrice: '',
            contractCount: '',
            contractSumPrice: '',
            contractUnitPrice: '',
            costUnitPrice: '',
            handedAmount: '',
            description: '',
            unitPrice: price,
            contractWorkVolume
          }
        })
      }
      this.targetList = formateData(obj.list)
    },
    getDocDetail(id) {
      getCompletionSettleInfoDetail({ CompletionSettleInfoId: id }).then(
        (res) => {
          const { lstAttachment, lstCompletionSettleDetail } = res.data || {}
          if (lstAttachment && lstAttachment.length > 0) {
            this.fileList = lstAttachment
          }
          if (
            lstCompletionSettleDetail &&
            lstCompletionSettleDetail.length > 0
          ) {
            this.targetList = lstCompletionSettleDetail
          }
        }
      )
    },
    deleteDetail() {},
    saveDoc() {
      if (this.optType === 'detai') {
        this.show = false
        return
      }
      this.$refs.form.validate((valid) => {
        if (valid) {
          const params = {
            completionSettleInfo: {
              ...this.form,
              ...(this.optType === 'edit'
                ? {
                  id: this.data.id
                }
                : {})
            },
            lstAttachment: this.fileList,
            lstCompletionSettleDetail: this.targetList.map((item) => {
              return {
                ...item,
                ...(this.optType === 'edit'
                  ? {
                    completionSettleInfoId: this.data.id
                  }
                  : {})
              }
            })
          }
          const fn =
            this.optType === 'add'
              ? addCompletionSettleInfo
              : updateCompletionSettleInfo
          fn(params).then((res) => {
            if (res.code === '0001') {
              this.$message({
                type: 'success',
                message: '保存成功!'
              })
              this.show = false
              this.$emit('freshList')
              this.$refs.form.resetFields()
            } else {
              this.$message({
                type: 'error',
                message: res.msg
              })
            }
          })
        }
      })
    },
    // 显示合价
    displaySumPrice() {
      this.$refs.detailTable.$refs.table.setCurrentRow()
    },
    // 获取合价
    getSumPrice() {
      if (this.selectRow) {
        let actualCompletion = 0
        let unitPrice = 0
        if (this.selectRow.actualCompletion) {
          actualCompletion = this.selectRow.actualCompletion
        }
        if (this.selectRow.unitPrice) {
          unitPrice = this.selectRow.unitPrice
        }
        const sumPrice = Number.parseFloat(unitPrice) * Number.parseFloat(actualCompletion)
        this.selectRow.sumPrice = sumPrice.toFixed(2)
      }
      // 获取项目结算金额
      this.getProjectSettleAmount()
    },
    // 获取项目结算金额
    getProjectSettleAmount() {
      let sum = 0
      const formateData = (data) => {
        data.forEach(item => {
          if (item.childrens) {
            formateData(item.childrens)
          }
          if (item.sumPrice) {
            sum += Number.parseFloat(item.sumPrice)
          }
        })
      }
      formateData(this.targetList)
      this.form.projectSettleAmount = sum.toFixed(2)
      this.$forceUpdate()
    }
  }
}
</script>

<style lang="scss" scoped>
.com-form-title {
  font-size: 14px;
  font-weight: bold;
  line-height: 35px;
  color: #409eff;
  border-bottom: 1px solid #dedede;
  margin-bottom: 6px;
}
</style>
